package org.goldfish.demo.multifrontend.messageboard.mobile.ui.views

import android.content.Intent
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Visibility
import androidx.compose.material.icons.filled.VisibilityOff
import androidx.compose.material3.Button
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.Text
import androidx.compose.material3.TextField
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.text.input.VisualTransformation
import androidx.compose.ui.unit.dp
import androidx.lifecycle.lifecycleScope
import kotlinx.coroutines.launch
import org.goldfish.demo.multifrontend.messageboard.mobile.model.LoginReq
import org.goldfish.demo.multifrontend.messageboard.mobile.network.ApiClient
import org.goldfish.demo.multifrontend.messageboard.mobile.network.ApiClient.auth
import org.goldfish.demo.multifrontend.messageboard.mobile.network.NetworkException
import retrofit2.HttpException
import java.io.IOException

class LoginActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        when (ApiClient.hasAuth) {
            true -> {
                startActivity(Intent(this, MessageActivity::class.java))
                finish()
                return
            }

            else -> {}
        }

        val (username, password) = auth
        setContent {
            LoginScreen(
                initialUsername = username,
                initialPassword = password,
                onRefreshUserInfo = { u, p, isRegister, onFinish ->
                    handleAuth(u, p, isRegister, onFinish)
                })
        }

    }

    private fun handleAuth(
        username: String,
        password: String,
        isRegister: Boolean,
        onFinish: () -> Unit,
    ) {
        val scope = lifecycleScope
        scope.launch {
            try {
                val req = LoginReq(username, password)
                auth(req, isRegister)
                startActivity(Intent(this@LoginActivity, MessageActivity::class.java))
                finish()
            } catch (e: HttpException) {
                NetworkException.handleHttpExceptionWithToast(
                    this@LoginActivity,
                    e,
                    clientErrorMessage = "客户端错误: 请检查用户名和密码",
                    serverErrorMessage = "服务器错误: 请联系管理员"
                )
            } catch (e: IOException) {
                NetworkException.handleNetworkExceptionWithToast(this@LoginActivity, e)
            } catch (e: Exception) {
                NetworkException.handleOtherExceptionWithToast(this@LoginActivity, e)
            } finally {
                onFinish()
            }
        }
    }
}


@Composable
fun LoginScreen(
    onRefreshUserInfo: (String, String, Boolean, onFinish: () -> Unit) -> Unit,
    initialUsername: String = "",
    initialPassword: String = "",
) {
    var username by rememberSaveable { mutableStateOf(initialUsername) }
    var password by rememberSaveable { mutableStateOf(initialPassword) }
    var isPasswordVisible by rememberSaveable { mutableStateOf(false) }
    var isLoading by remember { mutableStateOf(false) }

    val commonShape = RoundedCornerShape(10.dp)

    Column(
        modifier = Modifier
            .fillMaxSize()
            .padding(16.dp), verticalArrangement = Arrangement.Center
    ) {
        TextField(
            value = username,
            onValueChange = { username = it },
            label = { Text("用户名") },
            modifier = Modifier.fillMaxWidth(),
            shape = commonShape,
            singleLine = true,
            enabled = !isLoading,
        )
        Spacer(modifier = Modifier.height(8.dp))
        TextField(
            value = password,
            onValueChange = { password = it },
            label = { Text("密码") },
            modifier = Modifier.fillMaxWidth(),
            shape = commonShape,
            singleLine = true,
            visualTransformation = if (isPasswordVisible) VisualTransformation.None else PasswordVisualTransformation(),
            trailingIcon = {
                val image =
                    if (isPasswordVisible) Icons.Filled.VisibilityOff else Icons.Filled.Visibility
                val description = if (isPasswordVisible) "隐藏密码" else "显示密码"

                IconButton(onClick = { isPasswordVisible = !isPasswordVisible }) {
                    Icon(imageVector = image, contentDescription = description)
                }
            },
            enabled = !isLoading,
        )
        Spacer(modifier = Modifier.height(16.dp))
        Row {
            Button(
                onClick = {
                    isLoading = true
                    onRefreshUserInfo(username, password, false) { isLoading = false }
                },
                modifier = Modifier.weight(1f),
                shape = commonShape,
                enabled = !isLoading,
            ) {
                if (isLoading) {
                    CircularProgressIndicator(
                        modifier = Modifier
                            .width(20.dp)
                            .height(20.dp),
                        strokeWidth = 2.dp,
                    )
                } else {
                    Text("登录")
                }
            }
            Spacer(modifier = Modifier.width(8.dp))
            Button(
                onClick = {
                    isLoading = true
                    onRefreshUserInfo(username, password, true) { isLoading = false }
                },
                modifier = Modifier.weight(1f),
                shape = commonShape,
                enabled = !isLoading,
            ) {
                if (isLoading) {
                    CircularProgressIndicator(
                        modifier = Modifier
                            .width(20.dp)
                            .height(20.dp),
                        strokeWidth = 2.dp,
                    )
                } else {
                    Text("注册")
                }
            }
        }
    }
}

private const val TAG = "LoginActivity"
